package cn.qixin.passport.security;

import cn.qixin.passport.mapper.UserMapper;
import cn.qixin.passport.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security框架自动调用UserDetailsServiceImpl中的loadUserByUsername方法，参数：{}", s);
        UserLoginInfoVO userLogin = userMapper.getLoginInfoByUsername(s);

        log.debug("从数据库中根据用户名【{}】查询管理员信息，结果：{}", s, userLogin);
        if (userLogin == null){
            log.debug("没有与用户名【{}】匹配的管理员信息，即将抛出BadCredentialsException", s);
            String message = "登录失败，用户名不存在！";
            throw new BadCredentialsException(message);
        }

        log.debug("正在获取用户权限");
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : userLogin.getPermissions()) {
            GrantedAuthority authority =
                    new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
                QxUserDetails qxUserDetails = new QxUserDetails(
                        userLogin.getId(),
                        userLogin.getUsername(),
                        userLogin.getPassword(),
                        userLogin.getEnable() == 1,
                        authorities);
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", qxUserDetails);
            return qxUserDetails;
    }
}